import { Entity, Column, Index, BeforeInsert, OneToMany } from "typeorm";
import bcrypt from "bcryptjs";
import BaseEntity from "./base";
import { Post } from "./post";
import { Board } from "./board";
import { Comment } from "./comment";

export enum RoleUser {
  USER = "user",
  ADMIN = "admin",
}

@Entity("users")
export class User extends BaseEntity {
  @Index("name_index")
  @Column({
    unique: true,
  })
  name: string;

  @Index("email_index")
  @Column({
    unique: true,
  })
  email: string;

  @Column({ nullable: true })
  fullName: string;

  @Column({ nullable: true })
  description: string;

  @Column()
  password: string;

  @Column({
    type: "enum",
    enum: RoleUser,
    default: RoleUser.USER,
  })
  role: RoleUser.USER;

  @Column({
    default: "default.png",
  })
  photo: string;

  @OneToMany(() => Board, (board) => board.user)
  boards: Board[];

  @OneToMany(() => Post, (post) => post.user)
  posts: Post[];

  @OneToMany(() => Comment, (comment) => comment.user)
  comments: Comment[];

  @BeforeInsert()
  async hashPassword() {
    const salt = await bcrypt.genSalt(12);
    this.password = await bcrypt.hash(this.password, salt);
  }

  static async comparePasswords(
    candidatePassword: string,
    hashedPassword: string,
  ) {
    return await bcrypt.compare(candidatePassword, hashedPassword);
  }

  toJSON() {
    return { ...this, password: undefined };
  }
}
